import openpyxl
from openpyxl.chart import PieChart, Reference

# 准备数据
rows = [
    ['Pie', 'Sold'],
    ['Apple', 50],
    ['Cherry', 30],
    ['Pumpkin', 10],
    ['Chocolate', 40]
]

# 将数据写入Excel
workbook = openpyxl.Workbook()
worksheet = workbook.active

worksheet.title = 'Pie Chart'
for row in rows:
    worksheet.append(row)

# 绘制饼图
chart = PieChart()
chart.title = 'Pie Sold By Category'

category = Reference(worksheet, min_col=1, min_row=2, max_row=5)
data = Reference(worksheet, min_col=2, min_row=2, max_row=5)
# tips：先添加数据，在添加分类
chart.add_data(data)
chart.set_categories(category)

worksheet.add_chart(chart, 'D1')

# 保存工作簿
workbook.save('PieChart.xlsx')
